package server;

	import java.io.IOException;
import java.sql.Connection;
	import java.sql.DriverManager;
	import java.sql.PreparedStatement;
	import java.sql.ResultSet;
	import java.sql.SQLException;
	import java.sql.Statement;
import java.util.*;

import Log.Log;

	public class DBHandller {
		// --- Variables --- 
		Connection conn;
		
	
		// --- Constructors ----
		public DBHandller(String Host, String DBName, String UserName, String Password){
			try {
				makeConnection(Host,DBName,UserName,Password);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				Log.addError("Could not establish connection to db.. ");
			}
			
			
			
		}
	
		// --- methods --- 
		public void makeConnection(String Host,String DBName,String UserName,String Password) throws IOException {
			
			
			try 
			{
	            Class.forName("com.mysql.jdbc.Driver").newInstance();
	        } catch (Exception ex) {
	        	
	        	System.out.println("SQLException: ");
	        	throw new IOException();
	        }
	        
			
			
			try {
				conn  = DriverManager.getConnection("jdbc:mysql://"+Host+"/"+DBName,UserName,Password);
				//  conn = DriverManager.getConnection("jdbc:mysql://localhost/ass2","root","godmode");
			} catch (SQLException ex) {
				// TODO Auto-generated catch block
				ex.printStackTrace();
				System.out.println("SQLException: " + ex.getMessage());
	            System.out.println("SQLState: " + ex.getSQLState());
	            System.out.println("VendorError: " + ex.getErrorCode());
				throw new IOException();
			}
		
			
			
		}
		
		public void InsertDataToDb(String Table, String name, String price, String owner){
			Statement stmt;
			try {
				stmt = conn.createStatement();
			
				stmt.executeUpdate("Insert into "+ Table +" (name,price,owner) Values ('"+name+"','+"+price+"','"+owner+"')");
				stmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			//return false;
		}

		public ResultSet getTable(String Table) {
			// TODO Auto-generated method stub
			Statement stmt;
			try {
				stmt = conn.createStatement();
				return   stmt.executeQuery("select * from "+Table);

				//stmt.executeUpdate("Insert into "+ Table +" (name,price,owner) Values ('Table','32','Guy')");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
			
		}
		
		
	}

